/**
 * All Rights Reserved , Copyright (C) 2023 , 青岛鼎信通讯股份有限公司
 * <p>
 * QemProblemAlertController
 * 问题告警表
 * <p>
 * 修改纪录
 * 2023-01-06 版本：1.0 xinfushuo 创建。
 *
 * @version 版本：1.0
 * @author 作者：xinfushuo
 * 创建日期：2023-01-06
 */

package com.topscomm.qem.controller;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboItemDetailsEntity;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.cbo.service.impl.CboApprovalFlowInsService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.qem.controller.auto.QemProblemAlertControllerAuto;
import com.topscomm.qem.pojo.QemProblemAlertEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import static com.topscomm.qem.QemSystemConst.QmsBussinessManager;

/**
 * @author: xinfushuo
 * @date: 2023-01-06
 * @description:问题告警表Controller
 * @modify:
 */
@RestController
@RequestMapping("qms/qemProblemAlert")
public class QemProblemAlertController extends QemProblemAlertControllerAuto implements IQemProblemAlertController {

    @Autowired
    private CboApprovalFlowInsService cboApprovalFlowInsService;
    @Autowired
    ICboItemDetailsService cboItemDetailsService;

    public class Page_Type {
        public static final String manage = "manage";
        public static final String query = "query";
    }

    /**
     * @param paraMap
     * @return
     * @author: xinfushuo
     * @date: 2023-01-06
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        // 产品名称
        this.service.appendSql(paraMap, sql, "qry_productname", " and " + QemProblemAlertEntity.FieldProductname + " like '%{0}%'", value -> value);
        // 问题描述
        this.service.appendSql(paraMap, sql, "qry_problemdesc", " and " + QemProblemAlertEntity.FieldProblemdesc + " like '%{0}%'", value -> value);
        // 状态
        this.service.appendSql(paraMap, sql, "qry_state", " and " + QemProblemAlertEntity.FieldState + " = '{0}'", value -> value);
        // 单据开始日期
        this.service.appendSql(paraMap, sql, "qry_begindocdate", " and " + QemProblemAlertEntity.FieldDocdate + " >= {0}", value -> SQLAdapter.toDateLong(value + " 00:00:00"));
        // 单据结束日期
        this.service.appendSql(paraMap, sql, "qry_enddocdate", " and " + QemProblemAlertEntity.FieldDocdate + " <= {0}", value -> SQLAdapter.toDateLong(value + " 23:59:59"));
        // 其他条件
        this.service.appendSql(paraMap, sql, "qry_where", " and {0}", value -> value);
        // 问题分级
        this.service.appendSql(paraMap, sql, "qry_problemgrading", " and " + QemProblemAlertEntity.FieldProblemgrading + " = '{0}'", value -> value);
        // 问题编号
        this.service.appendSql(paraMap, sql, "qry_docno", " and " + QemProblemAlertEntity.FieldDocno + " like '%{0}%'", value -> value);
        // 申请人
        this.service.appendSql(paraMap, sql, "qry_usercode", " and " + QemProblemAlertEntity.FieldUsercode + " = '{0}'", value -> value);
        // 风险排查负责人
        this.service.appendSql(paraMap, sql, "qry_riskmancode", " and " + QemProblemAlertEntity.FieldRiskmancode + "  = '{0}'", value -> value);
        // 问题分析负责人
        this.service.appendSql(paraMap, sql, "qry_assayercode", " and " + QemProblemAlertEntity.FieldAssayercode + " = '{0}'", value -> value);
        // 告警主题
        this.service.appendSql(paraMap, sql, "qry_warningtitle", " and " + QemProblemAlertEntity.FieldWarningtitle + " like '%{0}%'", value -> value);
        // IPD节点
        this.service.appendSql(paraMap, sql, "qry_ipdnode", " and " + QemProblemAlertEntity.FieldIpdnode + " = '{0}'", value -> value);
        // 信息途径
        this.service.appendSql(paraMap, sql, "qry_pathway", " and " + QemProblemAlertEntity.FieldPathway + " = '{0}'", value -> value);
        // 是否重复发生
        this.service.appendSql(paraMap, sql, "qry_repeat", " and " + QemProblemAlertEntity.FieldRepeat + " = '{0}'", value -> value);
        // 违反质量政策
        this.service.appendSql(paraMap, sql, "qry_whetherqualitypolicy", " and " + QemProblemAlertEntity.FieldWhetherqualitypolicy + " = '{0}'", value -> value);
        // 牵头分析部门
        this.service.appendSql(paraMap, sql, "qry_dutydept", " and " + QemProblemAlertEntity.FieldDutydept + " = '{0}'", value -> value);
        // 问题归属产品线
        this.service.appendSql(paraMap, sql, "qry_productline", " and " + QemProblemAlertEntity.FieldProductline + " = '{0}'", value -> value);
        // 需求包
        this.service.appendSql(paraMap, sql, "qry_requirements", " and " + QemProblemAlertEntity.FieldRequirements + " = '{0}'", value -> value);
        // 问题发生环节
        this.service.appendSql(paraMap, sql, "qry_happennode", " and " + QemProblemAlertEntity.FieldHappennode + " = '{0}'", value -> value);
        // 作废
        this.service.appendSql(paraMap, sql, "qry_enabled", " and " + QemProblemAlertEntity.FieldEnabled + " != '{0}'", value -> value);
        // 发生地
        this.service.appendSql(paraMap, sql, "qry_occurred", " and " + QemProblemAlertEntity.FieldOccurred + " like '%{0}%'", value -> value);
        // 问题反馈人
        this.service.appendSql(paraMap, sql, "qry_feedbackpersoncode", " and " + QemProblemAlertEntity.FieldFeedbackpersoncode + "  = '{0}'", value -> value);
        if (paraMap.containsKey("qry_deptname")) {
            String value = paraMap.get("qry_deptname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and deptcode like '{0}%'", value);
        }
        //我的告警页控制参数
        if (paraMap.containsKey("qry_page")) {
            String value = paraMap.get("qry_page").toString();
            if (value.contentEquals(Page_Type.manage)) {
                    sql.appendSingle(" and ( ");
                    sql.appendSingle(QemProblemAlertEntity.FieldUsercode + " = '" + getUserBean().getUser().getCode() + "' ");
                    sql.appendSingle(" or " + QemProblemAlertEntity.FieldAssayercode + " = '" + getUserBean().getUser().getCode() + "' ");
                    sql.appendSingle(" or " + QemProblemAlertEntity.FieldRiskmancode + " = '" + getUserBean().getUser().getCode() + "' ");
                    sql.appendSingle(")");
            }
        }
        // 告警单管理页面控制参数
        if (paraMap.containsKey("qry_model")) {
            String value = paraMap.get("qry_model").toString();
            if (!StringUtil.isEmpty(value)) {
                if (value.equals("query")) {
                    // 如果权限为普通用户，则拼接权限控制
                    if (this.getUserBean().getUser().getAdminlevel() < 1 && !getUserBean().getRoleList().stream().map(CboRoleEntity::getCode).filter(Objects::nonNull).anyMatch(rolecode ->
                            rolecode.contentEquals(QmsBussinessManager))) {
                        sql.appendSingle(this.service.spellDataDutyDeptPermission());
                    }
                }
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: xinfushuo
     * @date: 2023-01-06
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @description: 提交审批前
     * @author: xinfushuo
     * @date: 2023-01-06
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交问题告警表申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
        System.out.println("push");
    }

    /**
     * @Description: 作废问题告警单
     * @Author: wuyuyang
     * @Return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date: 11/1/2023 下午10:13
     * @Version: 1.0
     **/
    @GetMapping(value = "/doCancel")
    public ResponseResult<Object> doCancel(@RequestParam(required = false) Map<String, Object> paraMap) {
        String id = ConvertUtil.convertToString(paraMap.get("id"));
        String cancelReason = ConvertUtil.convertToString(paraMap.get(QemProblemAlertEntity.FieldCancelreason));
        // 这里处理与问题告警单相关单据是否作废其他单据是否作废
        this.service.queryElseBillState(id);
        // 当作废原因和id不为空的情况下
        if(!StringUtils.isEmpty(id) && !StringUtils.isEmpty(cancelReason)) {
            Boolean res = this.service.executeCancel(id, cancelReason);
            if(res) {
                return ResponseResult.ok("作废成功！");
            } else {
                return ResponseResult.ok("作废失败！");
            }
        }
        return ResponseResult.error("参数错误、作废失败！");
    }

    @Override
    public ResponseResult<Object> dataCodeList(Map<String, Object> paraMap) {
        Map<String, Object> codeMap = new HashMap<String, Object>();

        List<Map<String, Object>> problemgradingList = datacodeCache.getCodeListMap("QemProblemgrading", "", "sortcode");
        codeMap.put("problemgradingList", problemgradingList);
        List<Map<String, Object>> sourcetypeList = datacodeCache.getCodeListMap("QemProblemSourcetype", "", "sortcode");
        codeMap.put("sourcetypeList", sourcetypeList);
        List<Map<String, Object>> happennodeList = datacodeCache.getCodeListMap("QemProblemHappennode", "", "sortcode");
        codeMap.put("happennodeList", happennodeList);
        List<Map<String, Object>> ipdnodeList = datacodeCache.getCodeListMap("QemProblemIpdnode", "", "sortcode");
        codeMap.put("ipdnodeList", ipdnodeList);
        List<Map<String, Object>> requirementsList = datacodeCache.getCodeListMap("QemProblemRequirements", "", "sortcode");
        codeMap.put("requirementsList", requirementsList);
        List<Map<String, Object>> pathwayList = datacodeCache.getCodeListMap("QemProblemPathway", "", "sortcode");
        codeMap.put("pathwayList", pathwayList);
        List<Map<String, Object>> emergenttreatmentList = datacodeCache.getCodeListMap("QemProblemEmergenttreatment", "", "sortcode");
        codeMap.put("emergenttreatmentList", emergenttreatmentList);
        List<Map<String, Object>> repeatList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
        codeMap.put("repeatList", repeatList);
        List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_QemProblemAlert", this.getUserBean(), "sortcode");
        codeMap.put("flowidList", flowidList);
        List<Map<String, Object>> stateList = datacodeCache.getCodeListMap("TapApprovalBillState", "", "sortcode");
        codeMap.put("stateList", stateList);
        List<Map<String, Object>> enabledList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
        codeMap.put("enabledList", enabledList);
        List<String> emailWhiteList = datacodeCache
                .getCodeListMap("QmsEmailWhiteList", "", "sortcode").stream().map(
                        item -> ConvertUtil.convertToString(item.get("name"))
                ).collect(Collectors.toList());
        codeMap.put("emailWhiteList", emailWhiteList);

        List<Map<String, Object>> formConfigList = cboItemDetailsService.queryMapByWhere(CboItemDetailsEntity.FieldItemid + " = (select id from Cboitems where code = 'ProblemAlertFormJson')");
        codeMap.put("formConfigList", formConfigList);
        super.dataCodeList(paraMap);
        return ResponseResult.ok(codeMap);
    }


    /**
     * @Description:    查询当前用户的直级领导,如果没找到不做任何处理
     * @Author:         wuyuyang
     * @Return:         com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @exception:
     * @Date:           2/2/2023 下午3:00
     * @Version:        1.0
     **/
    @GetMapping(value = "/queryDirectLeader")
    public ResponseResult<Object> queryDirectLeader() {
        HashMap<String, Object> map = this.service.queryDirectLeaderCode();
        return ResponseResult.ok(map);
    }
}

